﻿#include <QDir>
#include <QDebug>
#include <QMessageBox>
#include <QListView>
#include <QDateTime>
#include "common/Utils.h"
#include "common/DataType.h"
#include "MainWindow.h"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow),bConnectionState(false),m_CurrentMode(0)
{
    qInfo() << "__________________App Start__________________________";
    ui->setupUi(this);
    this->setFocus();

    /*********1.ini文件初始化*****************/
    QString documentsPath = QDir::tempPath();

    // 创建名为“024Matcher”的文件夹
    QString folderName = "024Matcher";
    QString folderPath = QDir(documentsPath).filePath(folderName);
    QDir dir(folderPath);

    if (!dir.exists()) {
        if (dir.mkdir(".")) {
            qDebug() << "文件夹创建成功：" << folderPath;
        } else {
            qDebug() << "文件夹创建失败";
        }
    } else {
        qDebug() << "文件夹已存在：" << folderPath;
    }

    // 获取并输出文件夹路径
    qDebug() << "Ini文件夹路径：" << folderPath;
    QString iniFilePath = folderPath + "/Settings.ini";

    m_Settings = new QSettings(iniFilePath,QSettings::IniFormat);

   m_Style = m_Settings->value("Style/Color","blue").toString();
   loadStyle(m_Style);

   m_CurrentMode = m_Settings->value("Record/CurrentMode",1).toUInt();//当前模式


   /*************2.线程初始化******************/
   m_Thread = new QThread();
   m_ModBusTcpWorker = new ModBusTcpWorker(nullptr,false);

   // 将 worker 移动到新线程，并确保在线程结束时删除
   m_ModBusTcpWorker->moveToThread(m_Thread);
   connect(m_Thread, &QThread::finished, m_Thread, &QObject::deleteLater);

   // 当 worker 被删除时，结束线程
   connect(m_ModBusTcpWorker, &QObject::destroyed, m_Thread, &QThread::quit);

   // 获取QCoreApplication的实例
   QCoreApplication *app = QCoreApplication::instance();
   if(app)
   {
       // 确保在应用程序退出时线程已经结束
       connect(app, &QCoreApplication::aboutToQuit, m_Thread, &QThread::quit);
       connect(m_Thread, &QThread::finished, app, &QCoreApplication::quit);
   }

   connect(this,&MainWindow::sig_SetProNameDevType,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetProNameDevType,Qt::QueuedConnection);
   connect(this,&MainWindow::sig_SetIPPort,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetIPPort,Qt::QueuedConnection);
   connect(this,&MainWindow::sig_SetReadStartAddressAndRegisterCount,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetReadStartAddressAndRegisterCount,Qt::QueuedConnection);
   connect(this,&MainWindow::sig_SetWriteStartAddressAndRegisterCount,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetWriteStartAddressAndRegisterCount,Qt::QueuedConnection);
   connect(this,&MainWindow::sig_StartLoopReadRegister,m_ModBusTcpWorker,&ModBusTcpWorker::slotStartConnection,Qt::QueuedConnection);
   connect(this,&MainWindow::sig_AddWriteQueue,m_ModBusTcpWorker,&ModBusTcpWorker::slotAddWriteQueue,Qt::QueuedConnection);

   connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_readBoolData,this,&MainWindow::slot_readBoolData,Qt::QueuedConnection);
   connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_readfloatData,this,&MainWindow::slot_readfloatData,Qt::QueuedConnection);
   connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_ConnectionState,this,&MainWindow::slot_ConnectionState,Qt::QueuedConnection);
   connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_WriteDataQueueFinish,this,&MainWindow::slot_WriteDataQueueFinish,Qt::QueuedConnection);

   //线程开始
   m_Thread->start();

   /*******设置子线程*******/
   //设置设备名称和类型ID 这个类被多次实例化区分使用，本次使用不上
   emit sig_SetProNameDevType("024Matcher",1);
   //emit sig_SetIPPort("192.168.1.100",502);

   QList<int> ReadStartAddressList; //开始地址的列表
   QList<int> ReadRegisterCountList;//开始地址的个数

   // 设置起始地址和寄存器个数  3为保持寄存器
   ReadStartAddressList  << 0  << 22 ;
   ReadRegisterCountList << 10 << 6  ;

   emit sig_SetReadStartAddressAndRegisterCount(ReadStartAddressList,ReadRegisterCountList,3);

   //开始循环读寄存器
   //emit sig_StartLoopReadRegister(true);



    /*************部分控件提升为成员变量**************/
    //找出三个禁用的widget排序存容器中
    QRegularExpression regex1("groupBox_Mode_\\d+");
    QList<QGroupBox*> groupModes = this->findChildren<QGroupBox*>(regex1);
    for(int i = 0; i < 3 ; i++)
    {
        foreach (QGroupBox* groupMode, groupModes)
        {
            if(groupMode->objectName() == QString("groupBox_Mode_%1").arg(i+1))
            {
                 m_WidgetModes << groupMode;
                 break;
            }
        }
    }


    /****************UI 的设置***************************/

    //添加IP验证器
    ui->lineEdit_IP->setValidator(new IPAddressValidator(this));

    m_SwtichStatusModePre_1 = false;
     for(int i = 0 ; i < 6;i++)//正反转  0 关 1开
         m_SwtichStatusModePre_2 << true;

     for(int i = 0 ; i < 16;i++)
     {
         m_SwtichStatusPre << false;
         m_LimitStatusPre << false;
         m_StepStatusPre << false;
     }

     ui->comboBox->setView(new QListView(this));
     if(m_CurrentMode >3)
         m_CurrentMode = 1;
     ui->comboBox->setCurrentIndex(m_CurrentMode-1);
     on_comboBox_currentIndexChanged(m_CurrentMode-1);

     m_AllBtns << findAllQPushButton(m_WidgetModes[0]);
     m_AllBtns << findAllQPushButton(m_WidgetModes[1]);
     m_AllBtns << findAllQPushButton(m_WidgetModes[2]);
     foreach(QList<QPushButton* > modBtns,m_AllBtns)//所有的按钮颜色置回去
     {
         foreach(QPushButton* btn,modBtns)
             btn->setStyleSheet(BtnRunBlue);
     }

     m_AllStateBtns.append( ui->groupBox_2->findChildren<QPushButton*>());
     m_AllStateBtns.append( ui->groupBox_3->findChildren<QPushButton*>());

     setEnableAllChildWidgets(m_WidgetModes[0],false);
     setEnableAllChildWidgets(m_WidgetModes[1],false);
     setEnableAllChildWidgets(m_WidgetModes[2],false);

     ui->dSBox_ATargetValue->blockSignals(true);
     ui->dSBox_MTargetValue_1->blockSignals(true);
     ui->dSBox_MTargetValue_2->blockSignals(true);
     ui->dSBox_MTargetValue_3->blockSignals(true);
     ui->spBox_StepValue_1->blockSignals(true);
     ui->spBox_StepValue_2->blockSignals(true);
     ui->spBox_StepValue_3->blockSignals(true);
     ui->dSpinBox_speed->blockSignals(true);

     ui->dSpinBox_speed->setValue( m_Settings->value("Data/Speed").toFloat());
     ui->dSBox_ATargetValue->setValue( m_Settings->value("Mode1/Value").toFloat());
     ui->dSBox_MTargetValue_1->setValue( m_Settings->value("Mode2/Value1").toFloat());
     ui->dSBox_MTargetValue_2->setValue( m_Settings->value("Mode2/Value2").toFloat());
     ui->dSBox_MTargetValue_3->setValue( m_Settings->value("Mode2/Value3").toFloat());
     ui->spBox_StepValue_1->setValue( m_Settings->value("Mode3/Value1").toFloat());
     ui->spBox_StepValue_2->setValue( m_Settings->value("Mode3/Value2").toFloat());
     ui->spBox_StepValue_3->setValue( m_Settings->value("Mode3/Value3").toFloat());

     ui->dSBox_ATargetValue->blockSignals(false);
     ui->dSBox_MTargetValue_1->blockSignals(false);
     ui->dSBox_MTargetValue_2->blockSignals(false);
     ui->dSBox_MTargetValue_3->blockSignals(false);
     ui->spBox_StepValue_1->blockSignals(false);
     ui->spBox_StepValue_2->blockSignals(false);
     ui->spBox_StepValue_3->blockSignals(false);
     ui->btn_Write->setEnabled(false);
     ui->dSpinBox_speed->blockSignals(false);

     this->setWindowTitle("024匹配器");

     //qDebug() << "getHardDiskSerialNumber:" << getHardDiskSerialNumber();
}

MainWindow::~MainWindow()
{
    qInfo() << "__________________App Exit __________________________";
    delete ui;
}

void MainWindow::slot_readBoolData(int MsgId, QList<bool> data)
{
    switch (MsgId) {
    case 11://寄存器起始地址0 个数1 状态信息
    {
        if(data.size() != 16)
            return;

        switch (m_CurrentMode) {//区分当前的模式
        case 1:
            //qDebug() << "200ms：" << QDateTime::currentDateTime();
            if(data[0] != m_SwtichStatusModePre_1)//不等于上一个
            {
                if(data[0])
                    ui->btn_ARun->setStyleSheet(BtnRunBlueGreen);
                else
                    ui->btn_ARun->setStyleSheet(BtnRunBlue);
            }
            m_SwtichStatusModePre_1 = data[0];
            break;

        case 2:
            if(data[1] != m_SwtichStatusModePre_2[0])
            {
                if(data[1])
                    ui->btn_FRotation_1->setStyleSheet(BtnRunBlueGreen);
                else
                    ui->btn_FRotation_1->setStyleSheet(BtnRunBlue);
            }

            if(data[2] != m_SwtichStatusModePre_2[1])
            {
                if(data[2])
                    ui->btn_RRotation_1->setStyleSheet(BtnRunBlueGreen);
                else
                    ui->btn_RRotation_1->setStyleSheet(BtnRunBlue);
            }

            if(data[3] != m_SwtichStatusModePre_2[2])
            {
                if(data[3])
                    ui->btn_FRotation_2->setStyleSheet(BtnRunBlueGreen);
                else
                    ui->btn_FRotation_2->setStyleSheet(BtnRunBlue);
            }
            if(data[4] != m_SwtichStatusModePre_2[3])
            {
                if(data[4])
                    ui->btn_RRotation_2->setStyleSheet(BtnRunBlueGreen);
                else
                    ui->btn_RRotation_2->setStyleSheet(BtnRunBlue);
            }

            if(data[5] != m_SwtichStatusModePre_2[4])
            {
                if(data[5])
                    ui->btn_FRotation_3->setStyleSheet(BtnRunBlueGreen);
                else
                    ui->btn_FRotation_3->setStyleSheet(BtnRunBlue);
            }

            if(data[6] != m_SwtichStatusModePre_2[5])
            {
                if(data[6])
                    ui->btn_RRotation_3->setStyleSheet(BtnRunBlueGreen);
                else
                    ui->btn_RRotation_3->setStyleSheet(BtnRunBlue);
            }
            m_SwtichStatusModePre_2.clear();
            for(int i = 1 ;i <= 6;i ++)
                m_SwtichStatusModePre_2 << data[i];
            break;

        case 3:

            break;
        default:
            break;
        }
        m_SwtichStatusPre = data;
    }
        break;
    /*
    case 12://电机1-3错误屏蔽
        //qDebug() << "data12:" << data;
        break;

    case 13://电机1-3错误指示
        //qDebug() << "data13:" << data;
        break;
    */
    case 14://电机1-3限位指示1-2  运动指示、匹配完成和手动匹配
    {
        if(data.size() != 16)
            return;

        QMap<int, bool> result = compareQListBool(m_LimitStatusPre,data);
        for (auto it = result.constBegin(); it != result.constEnd(); ++it)
        {
            int key = it.key();
            bool value = it.value();
            // 处理键值对
            //qDebug() << "Key:" << key << "Value:" << value;

            switch (key) {
            case 0:
                ui->btn_fault_1->setChecked(value);
                break;
            case 1:
                ui->btn_fault_2->setChecked(value);
                break;
            case 2:
                ui->btn_fault_3->setChecked(value);
                break;
            case 3:
                ui->btn_fault_4->setChecked(value);
                break;
            case 4:
                ui->btn_fault_5->setChecked(value);
                break;
            case 5:
                ui->btn_fault_6->setChecked(value);
                break;
            case 6:
                ui->btn_State_1->setChecked(value);
                break;
            case 7:
                ui->btn_State_2->setChecked(value);
                break;
            case 8:
                ui->btn_State_3->setChecked(value);
                break;
            case 9:
                ui->btn_State_4->setChecked(value);
                break;
            case 10://电机1手动匹配
                if(value)
                    ui->btn_MRun_1->setStyleSheet(BtnRunBlueGreen);
                else
                    ui->btn_MRun_1->setStyleSheet(BtnRunBlue);
                break;

            case 11://电机2手动匹配
                if(value)
                    ui->btn_MRun_2->setStyleSheet(BtnRunBlueGreen);
                else
                    ui->btn_MRun_2->setStyleSheet(BtnRunBlue);
                break;

            case 12://电机2手动匹配
                if(value)
                    ui->btn_MRun_3->setStyleSheet(BtnRunBlueGreen);
                else
                    ui->btn_MRun_3->setStyleSheet(BtnRunBlue);
                break;

            default:
                break;
            }

        }

        m_LimitStatusPre = data;
    }
        break;

    case 15://步进的记录
        m_StepStatusPre = data;
        break;

    default:
        break;
    }
}

void MainWindow::slot_readfloatData(int MsgId, QList<float> data)
{
    switch (MsgId) {
    case 21:
        if(data.size() != 2)
            return;
        ui->dSpinBox_value_1->setValue(data.at(0));
        ui->dSpinBox_value_2->setValue(data.at(1));
        break;

    case 22:
        if(data.size() != 3)
            return;
        ui->dSpinBox_value_3->setValue(data.at(0));
        ui->dSpinBox_value_4->setValue(data.at(1));
        ui->dSpinBox_value_5->setValue(data.at(2));
        break;
    default:
        break;
    }
}

//下位机连接成功反馈
void MainWindow::slot_ConnectionState(bool isConnectionState)
{
    bConnectionState = isConnectionState;
    if(bConnectionState)
    {
        ui->statusbar->showMessage("连接成功",2500);
        ui->btn_Link->setText("已连接");
        m_Settings->setValue("IPSetting/IP",ui->lineEdit_IP->text());
        m_Settings->setValue("IPSetting/Port",ui->spinBox_Port->value());
        ui->lineEdit_IP->setEnabled(false);
        ui->spinBox_Port->setEnabled(false);
        ui->btn_Write->setEnabled(true);
        ui->btn_Link->setStyleSheet(BtnRunBlue);//蓝色

        switch (m_CurrentMode) {
        case 1:
        {
            //模式2所有的按钮颜色置回去
            foreach(QPushButton* btn,m_AllBtns[1])
                btn->setStyleSheet(BtnRunBlue);

            setEnableAllChildWidgets(m_WidgetModes[0],true);
            setEnableAllChildWidgets(m_WidgetModes[1],false);
            setEnableAllChildWidgets(m_WidgetModes[2],false);

            //发送模式
            QList<quint16> sendData;
            sendData << static_cast<quint16>(0);
            WriteData* writeData1 = new WriteData(40,sendData.size(),sendData);
            emit sig_AddWriteQueue(writeData1);

            //发送自动模式目标最小电压
            sendData.clear();
            float fValue = static_cast<float>(ui->dSBox_ATargetValue->value());
            sendData << floatToQuint16(fValue);
            WriteData* writeData2 = new WriteData(12,sendData.size(),sendData);
            emit sig_AddWriteQueue(writeData2);


            break;
        }
        case 2:
        {
            //模式一所有的按钮颜色置回去
            foreach(QPushButton* btn,m_AllBtns[0])
                btn->setStyleSheet(BtnRunBlue);

            setEnableAllChildWidgets(m_WidgetModes[0],false);
            setEnableAllChildWidgets(m_WidgetModes[1],true);
            setEnableAllChildWidgets(m_WidgetModes[2],false);

            //发送模式
            QList<quint16> sendData;
            sendData << static_cast<quint16>(1);
            WriteData* writeData1 = new WriteData(40,sendData.size(),sendData);
            emit sig_AddWriteQueue(writeData1);

//            //发送手动模式电机1目标最小电压
//            sendData.clear();
//            sendData << floatToQuint16(static_cast<float>(ui->dSBox_MTargetValue_1->value()));
//            sendData << floatToQuint16(static_cast<float>(ui->dSBox_MTargetValue_2->value()));
//            sendData << floatToQuint16(static_cast<float>(ui->dSBox_MTargetValue_3->value()));
//            WriteData* writeData2 = new WriteData(68,sendData.size(),sendData);
//            emit sig_AddWriteQueue(writeData2);

        }
            break;
        case 3:
        {
            //模式1和模式2 所有的按钮颜色置回去
            foreach(QPushButton* btn,m_AllBtns[0])
                btn->setStyleSheet(BtnRunBlue);
            foreach(QPushButton* btn,m_AllBtns[1])
                btn->setStyleSheet(BtnRunBlue);

            setEnableAllChildWidgets(m_WidgetModes[0],false);
            setEnableAllChildWidgets(m_WidgetModes[1],false);
            setEnableAllChildWidgets(m_WidgetModes[2],true);

            //发送模式
            QList<quint16> sendData;
            sendData << static_cast<quint16>(2);
            WriteData* writeData1 = new WriteData(40,sendData.size(),sendData);
            emit sig_AddWriteQueue(writeData1);

            //发送步进数值
            sendData.clear();
            sendData.append( quint32toQuint16List (static_cast<quint32>(ui->spBox_StepValue_1->value())));
            sendData.append( quint32toQuint16List (static_cast<quint32>(ui->spBox_StepValue_2->value())));
            sendData.append( quint32toQuint16List (static_cast<quint32>(ui->spBox_StepValue_3->value())));

            WriteData* writeData2 = new WriteData(56,sendData.size(),sendData);
            emit sig_AddWriteQueue(writeData2);

        }
            break;
        default:
            break;
        }

    }
    else
    {
        ui->statusbar->showMessage("连接失败",2500);
        ui->btn_Link->setText("连接");
        ui->lineEdit_IP->setEnabled(true);
        ui->spinBox_Port->setEnabled(true);
        ui->btn_Write->setEnabled(false);
        ui->btn_Link->setStyleSheet(BtnRunGray);//灰色

        //模式1和模式2 所有的按钮颜色置回去
        foreach(QPushButton* btn,m_AllBtns[0])
            btn->setStyleSheet(BtnRunBlue);
        foreach(QPushButton* btn,m_AllBtns[1])
            btn->setStyleSheet(BtnRunBlue);
        foreach(QPushButton* btn,m_AllStateBtns)//所有的按钮颜色置回去
            btn->setChecked(false);

        setEnableAllChildWidgets(m_WidgetModes[0],false);
        setEnableAllChildWidgets(m_WidgetModes[1],false);
        setEnableAllChildWidgets(m_WidgetModes[2],false);

        //离线状态置回默认
        m_SwtichStatusModePre_1 = false;
        for(int i = 0;i<6;i++)
            m_SwtichStatusModePre_2[i] = false; // 1开 0关
        for(int i = 0;i<16;i++)
            m_LimitStatusPre[i] = false;




    }
    ui->btn_LinkState->setChecked(bConnectionState);
}

void MainWindow::slot_WriteDataQueueFinish()
{
    ui->statusbar->showMessage("写入完成",2500);
}

//样式
void MainWindow::loadStyle(QString currentStyle)
{
    QString styleFileName;
    if(currentStyle == "blue")
    {
        styleFileName = ":/res/qss/blueStyle.css";
    }
    else if(currentStyle == "black")
    {
        styleFileName = ":/res/qss/style.css";
    }
    else if(currentStyle == "gray")
    {
        styleFileName = ":/res/qss/grayStyle.css";
    }
    else if(currentStyle == "white")
    {
        styleFileName = ":/res/qss/whiteStyle.css";
    }
    else if(currentStyle == "original")
    {
        qApp->setStyleSheet("");
        return;
    }
    else
    {
        return;
    }
    QString style;
    if (!QFileInfo::exists(styleFileName))
    {
        return;
    }
    QFile fh(styleFileName);
    if (fh.open(QFile::ReadOnly | QFile::Text))
    {
        style = fh.readAll();
        fh.close();
    }
    else
    {
        qWarning()<<"open file"<<styleFileName<<"error!";
    }
    qApp->setStyleSheet(style);
}


//点击连接设备
void MainWindow::on_btn_Link_clicked()
{
    if (!ui->lineEdit_IP->hasAcceptableInput())
    {
        QMessageBox::warning(this, "IP地址提示", "请正确输入IP");
        return;
    }

    if(ui->btn_Link->text() == "连接")
    {
        emit sig_SetIPPort(ui->lineEdit_IP->text(),ui->spinBox_Port->value());
        emit sig_StartLoopReadRegister(true);
    }
    else if(ui->btn_Link->text() == "已连接")
    {
        emit sig_StartLoopReadRegister(false);
    }
}

void MainWindow::on_comboBox_currentIndexChanged(int index)
{
    if(index < 0)
        index = 0;
    if(index > 2)
        index = 2;
    m_CurrentMode = index +1;
    m_Settings->setValue("Record/CurrentMode",m_CurrentMode);//当前模式

    //0自动 1 手动 2 步进
    switch (index) {
    case 0:
    {
        if(bConnectionState)
        {
            //发送模式
            QList<quint16> sendData;
            sendData << static_cast<quint16>(index);
            WriteData* writeData1 = new WriteData(40,sendData.size(),sendData);
            emit sig_AddWriteQueue(writeData1);

            //发送自动模式目标最小电压
            sendData.clear();
            float fValue = static_cast<float>(ui->dSBox_ATargetValue->value());
            sendData << floatToQuint16(fValue);
            WriteData* writeData2 = new WriteData(12,sendData.size(),sendData);
            emit sig_AddWriteQueue(writeData2);

            //模式模式2 所有的按钮颜色置回去
            foreach(QPushButton* btn,m_AllBtns[1])
                btn->setStyleSheet(BtnRunBlue);

            setEnableAllChildWidgets(m_WidgetModes[0],true);
            setEnableAllChildWidgets(m_WidgetModes[1],false);
            setEnableAllChildWidgets(m_WidgetModes[2],false);

            for(int i = 0;i<6;i++)
                m_SwtichStatusModePre_2[i] = false;// 1 开 0 关
        }

        break;
    }
    case 1:
    {
        if(bConnectionState)
        {
            //发送模式
            QList<quint16> sendData;
            sendData << static_cast<quint16>(index);
            WriteData* writeData1 = new WriteData(40,sendData.size(),sendData);
            emit sig_AddWriteQueue(writeData1);

//            //发送手动模式电机1目标最小电压
//            sendData.clear();
//            sendData << floatToQuint16(static_cast<float>(ui->dSBox_MTargetValue_1->value()));
//            sendData << floatToQuint16(static_cast<float>(ui->dSBox_MTargetValue_2->value()));
//            sendData << floatToQuint16(static_cast<float>(ui->dSBox_MTargetValue_3->value()));
//            WriteData* writeData2 = new WriteData(68,sendData.size(),sendData);
//            emit sig_AddWriteQueue(writeData2);

            //模式1所有的按钮颜色置回去
            foreach(QPushButton* btn,m_AllBtns[0])
                btn->setStyleSheet(BtnRunBlue);

            setEnableAllChildWidgets(m_WidgetModes[0],false);
            setEnableAllChildWidgets(m_WidgetModes[1],true);
            setEnableAllChildWidgets(m_WidgetModes[2],false);

            m_SwtichStatusModePre_1 = false;
        }

    }
        break;
    case 2:
    {
        if(bConnectionState)
        {
            //发送模式
            QList<quint16> sendData;
            sendData << static_cast<quint16>(index);
            WriteData* writeData1 = new WriteData(40,sendData.size(),sendData);
            emit sig_AddWriteQueue(writeData1);

            //发送步进数值
            sendData.clear();
            sendData.append( quint32toQuint16List (static_cast<quint32>(ui->spBox_StepValue_1->value())));
            sendData.append( quint32toQuint16List (static_cast<quint32>(ui->spBox_StepValue_2->value())));
            sendData.append( quint32toQuint16List (static_cast<quint32>(ui->spBox_StepValue_3->value())));
            WriteData* writeData2 = new WriteData(56,sendData.size(),sendData);
            emit sig_AddWriteQueue(writeData2);

            //模式1和模式2 所有的按钮颜色置回去
            foreach(QPushButton* btn,m_AllBtns[0])
                btn->setStyleSheet(BtnRunBlue);
            foreach(QPushButton* btn,m_AllBtns[1])
                btn->setStyleSheet(BtnRunBlue);

            setEnableAllChildWidgets(m_WidgetModes[0],false);
            setEnableAllChildWidgets(m_WidgetModes[1],false);
            setEnableAllChildWidgets(m_WidgetModes[2],true);

            m_SwtichStatusModePre_1 = false;
            for(int i = 0;i<6;i++)
                m_SwtichStatusModePre_2[i] = false; // 1开 0关
        }

    }
        break;
    default:
        break;
    }
}

//自动模式运行
void MainWindow::on_btn_ARun_clicked()
{
    if(m_SwtichStatusPre.size() != 16)
        return;

    //自动模式目标最小电压
    QList<quint16> sendData;
    if(!m_SwtichStatusPre.at(0))
    {
        float fValue = static_cast<float>(ui->dSBox_ATargetValue->value());
        sendData << floatToQuint16(fValue);
        WriteData* writeData1 = new WriteData(12,sendData.size(),sendData);
        emit sig_AddWriteQueue(writeData1);
    }
    //取上次读的记录
    QList<bool> tempSwtichStatusPre = m_SwtichStatusPre;//取反
    tempSwtichStatusPre[0] = !tempSwtichStatusPre[0];

    //发送运行
    sendData.clear();
    sendData << boolListToQuint16(tempSwtichStatusPre);
    WriteData* writeData2 = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData2);
}

//电机1正转
void MainWindow::on_btn_FRotation_1_clicked()
{
    if(m_SwtichStatusPre.size() != 16)
        return;
    //取反
    QList<bool> tempSwtichStatusPre = m_SwtichStatusPre;
    tempSwtichStatusPre[1] = !tempSwtichStatusPre[1];

    //正转和反转加互斥 0开1关
    if(tempSwtichStatusPre[1] && tempSwtichStatusPre[2])
    {
        tempSwtichStatusPre[2] = false;
    }

    QList<quint16> sendData;
    sendData << boolListToQuint16(tempSwtichStatusPre);
    WriteData* writeData = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData);
}

//电机1反转
void MainWindow::on_btn_RRotation_1_clicked()
{
    if(m_SwtichStatusPre.size() != 16)
        return;

    //取反
    QList<bool> tempSwtichStatusPre = m_SwtichStatusPre;
    tempSwtichStatusPre[2] = !tempSwtichStatusPre[2];

    //正转和反转加互斥 0开1关
    if(tempSwtichStatusPre[1] && tempSwtichStatusPre[2])
    {
        tempSwtichStatusPre[1] = false;
    }

    QList<quint16> sendData;
    sendData << boolListToQuint16(tempSwtichStatusPre);
    WriteData* writeData = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData);
}

//电机2正转
void MainWindow::on_btn_FRotation_2_clicked()
{
    if(m_SwtichStatusPre.size() != 16)
        return;

    //取反
    QList<bool> tempSwtichStatusPre = m_SwtichStatusPre;
    tempSwtichStatusPre[3] = !tempSwtichStatusPre[3];

    //正转和反转加互斥 0开1关
    if(tempSwtichStatusPre[3] && tempSwtichStatusPre[4])
    {
        tempSwtichStatusPre[4] = false;
    }


    QList<quint16> sendData;
    sendData << boolListToQuint16(tempSwtichStatusPre);
    WriteData* writeData = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData);
}

//电机2反转
void MainWindow::on_btn_RRotation_2_clicked()
{
    if(m_SwtichStatusPre.size() != 16)
        return;

    //取反
    QList<bool> tempSwtichStatusPre = m_SwtichStatusPre;
    tempSwtichStatusPre[4] = !tempSwtichStatusPre[4];

    //正转和反转加互斥
    if(tempSwtichStatusPre[3] && tempSwtichStatusPre[4])
    {
        tempSwtichStatusPre[3] = false;
    }

    QList<quint16> sendData;
    sendData << boolListToQuint16(tempSwtichStatusPre);
    WriteData* writeData = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData);
}

//电机3正转
void MainWindow::on_btn_FRotation_3_clicked()
{
    if(m_SwtichStatusPre.size() != 16)
        return;

    //取反
    QList<bool> tempSwtichStatusPre = m_SwtichStatusPre;
    tempSwtichStatusPre[5] = !tempSwtichStatusPre[5];

    //正转和反转加互斥 0开1关
    if(tempSwtichStatusPre[5] && tempSwtichStatusPre[6])
    {
        tempSwtichStatusPre[6] = false;
    }

    QList<quint16> sendData;
    sendData << boolListToQuint16(tempSwtichStatusPre);
    WriteData* writeData = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData);
}

//电机3反转
void MainWindow::on_btn_RRotation_3_clicked()
{
    if(m_SwtichStatusPre.size() != 16)
        return;

    //取反
    QList<bool> tempSwtichStatusPre = m_SwtichStatusPre;
    tempSwtichStatusPre[6] = !tempSwtichStatusPre[6];

    //正转和反转加互斥 0开1关
    if(tempSwtichStatusPre[5] && tempSwtichStatusPre[6])
    {
        tempSwtichStatusPre[5] = false;
    }

    QList<quint16> sendData;
    sendData << boolListToQuint16(tempSwtichStatusPre);
    WriteData* writeData = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData);
}

//电机1手动匹配
void MainWindow::on_btn_MRun_1_clicked()
{
    if(m_LimitStatusPre.size() != 16)
        return;

    //手动模式电机1目标电压
    QList<quint16> sendData;
    if(!m_LimitStatusPre.at(10))
    {
        float fValue = static_cast<float>(ui->dSBox_MTargetValue_1->value());
        sendData << floatToQuint16(fValue);
        WriteData* writeData1 = new WriteData(68,sendData.size(),sendData);
        emit sig_AddWriteQueue(writeData1);
    }

    //取反
    /*
    QList<bool> tempSwtichStatusPre = m_LimitStatusPre;
    tempSwtichStatusPre[10] = !tempSwtichStatusPre[10];

    sendData.clear();
    sendData << boolListToQuint16(tempSwtichStatusPre);
    WriteData* writeData2 = new WriteData(3,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData2);
    */

}

//电机2手动匹配
void MainWindow::on_btn_MRun_2_clicked()
{
    if(m_LimitStatusPre.size() != 16)
        return;

    //手动模式电机1目标电压
    QList<quint16> sendData;
    if(!m_LimitStatusPre.at(11))
    {
        float fValue = static_cast<float>(ui->dSBox_MTargetValue_2->value());
        sendData << floatToQuint16(fValue);
        WriteData* writeData1 = new WriteData(70,sendData.size(),sendData);
        emit sig_AddWriteQueue(writeData1);
    }

    //取反
    /*
    QList<bool> tempSwtichStatusPre = m_LimitStatusPre;
    tempSwtichStatusPre[11] = !tempSwtichStatusPre[11];

    sendData.clear();
    sendData << boolListToQuint16(tempSwtichStatusPre);
    WriteData* writeData2 = new WriteData(3,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData2);
    */
}

//电机3手动匹配
void MainWindow::on_btn_MRun_3_clicked()
{
    if(m_LimitStatusPre.size() != 16)
        return;

    //手动模式电机1目标电压
    QList<quint16> sendData;
    if(!m_LimitStatusPre.at(12))
    {
        float fValue = static_cast<float>(ui->dSBox_MTargetValue_3->value());
        sendData << floatToQuint16(fValue);
        WriteData* writeData1 = new WriteData(72,sendData.size(),sendData);
        emit sig_AddWriteQueue(writeData1);
    }

    //取反
    /*
    QList<bool> tempSwtichStatusPre = m_LimitStatusPre;
    tempSwtichStatusPre[12] = !tempSwtichStatusPre[12];

    sendData.clear();
    sendData << boolListToQuint16(tempSwtichStatusPre);
    WriteData* writeData2 = new WriteData(3,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData2);
    */
}

//步进电机1正转
void MainWindow::on_btn_SFRotation_1_clicked()
{
    if(m_StepStatusPre.size() != 16)
        return;
    QList<quint16> sendData;
    //设置为正
    QList<bool> tempStepStatusPre = m_StepStatusPre;
    if(!tempStepStatusPre[0])
        tempStepStatusPre[0] = true;

    sendData.clear();
    sendData << boolListToQuint16(tempStepStatusPre);
    WriteData* writeData2 = new WriteData(4,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData2);

}

//步进电机1反转
void MainWindow::on_btn_SRRotation_1_clicked()
{
    if(m_StepStatusPre.size() != 16)
        return;

    QList<quint16> sendData;
    //取反
    QList<bool> tempStepStatusPre = m_StepStatusPre;
    if(!tempStepStatusPre[1])
        tempStepStatusPre[1] = true;

    sendData.clear();
    sendData << boolListToQuint16(tempStepStatusPre);
    WriteData* writeData2 = new WriteData(4,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData2);

}

//步进电机2正转
void MainWindow::on_btn_SFRotation_2_clicked()
{
    if(m_StepStatusPre.size() != 16)
        return;

    QList<quint16> sendData;

    //取反
    QList<bool> tempStepStatusPre = m_StepStatusPre;
    if(!tempStepStatusPre[2])
        tempStepStatusPre[2] = true;

    sendData.clear();
    sendData << boolListToQuint16(tempStepStatusPre);
    WriteData* writeData2 = new WriteData(4,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData2);
}

//步进电机2反转
void MainWindow::on_btn_SRRotation_2_clicked()
{
    if(m_StepStatusPre.size() != 16)
        return;
    QList<quint16> sendData;

    //取反
    QList<bool> tempStepStatusPre = m_StepStatusPre;
    if(!tempStepStatusPre[3])
        tempStepStatusPre[3] = true;

    sendData.clear();
    sendData << boolListToQuint16(tempStepStatusPre);
    WriteData* writeData2 = new WriteData(4,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData2);
}

//步进电机3正转
void MainWindow::on_btn_SFRotation_3_clicked()
{
    if(m_StepStatusPre.size() != 16)
        return;
    QList<quint16> sendData;

    //取反
    QList<bool> tempStepStatusPre = m_StepStatusPre;
    if(!tempStepStatusPre[4])
        tempStepStatusPre[4] = true;

    sendData.clear();
    sendData << boolListToQuint16(tempStepStatusPre);
    WriteData* writeData2 = new WriteData(4,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData2);
}

//步进电机3反转
void MainWindow::on_btn_SRRotation_3_clicked()
{
    if(m_StepStatusPre.size() != 16)
        return;
    QList<quint16> sendData;

    //取反
    QList<bool> tempStepStatusPre = m_StepStatusPre;
    if(!tempStepStatusPre[5])
        tempStepStatusPre[5] = true;

    sendData.clear();
    sendData << boolListToQuint16(tempStepStatusPre);
    WriteData* writeData2 = new WriteData(4,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData2);
}

void MainWindow::on_dSBox_ATargetValue_valueChanged(double arg1)
{
    m_Settings->setValue("Mode1/Value",arg1);
}


void MainWindow::on_dSBox_MTargetValue_1_valueChanged(double arg1)
{
    m_Settings->setValue("Mode2/Value1",arg1);
}


void MainWindow::on_dSBox_MTargetValue_2_valueChanged(double arg1)
{
     m_Settings->setValue("Mode2/Value2",arg1);
}

void MainWindow::on_dSBox_MTargetValue_3_valueChanged(double arg1)
{
    m_Settings->setValue("Mode2/Value3",arg1);
}

void MainWindow::on_spBox_StepValue_1_valueChanged(int arg1)
{
    m_Settings->setValue("Mode3/Value1",arg1);
}

void MainWindow::on_spBox_StepValue_2_valueChanged(int arg1)
{
    m_Settings->setValue("Mode3/Value2",arg1);
}

void MainWindow::on_spBox_StepValue_3_valueChanged(int arg1)
{
    m_Settings->setValue("Mode3/Value3",arg1);
}

void MainWindow::on_btn_Write_clicked()
{
    if(!bConnectionState)
        return;
    //电机2步进数
    QList<quint16> sendData;
    float fValue = static_cast<float>(ui->dSpinBox_speed->value());
    sendData << floatToQuint16(fValue);
    WriteData* writeData1 = new WriteData(10,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData1);
    m_Settings->setValue("Data/Speed",ui->dSpinBox_speed->value());
}

void MainWindow::on_btn_SetStep_1_clicked()
{
    //电机1步进数
    QList<quint16> sendData;
    quint32 iValue = static_cast<quint32>(ui->spBox_StepValue_1->value());
    sendData << quint32toQuint16List(iValue);
    WriteData* writeData1 = new WriteData(56,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData1);
}

void MainWindow::on_btn_SetStep_2_clicked()
{
    //电机2步进数
    QList<quint16> sendData;
    quint32 iValue = static_cast<quint32>(ui->spBox_StepValue_2->value());
    sendData << quint32toQuint16List(iValue);
    WriteData* writeData1 = new WriteData(58,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData1);
}

void MainWindow::on_btn_SetStep_3_clicked()
{
    //电机3步进数
    QList<quint16> sendData;
    quint32 iValue = static_cast<quint32>(ui->spBox_StepValue_3->value());
    sendData << quint32toQuint16List(iValue);
    WriteData* writeData1 = new WriteData(60,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData1);
}
